package com.bytedance.tts.demo;

import com.alibaba.fastjson.JSON;
import okhttp3.*;

import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicProgressBarUI;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class TTSApp {
    private JFrame frame;
    private JTextField textField;
    private JProgressBar progressBar;
    private JButton orderButton;
    private JButton reverseButton;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                UIManager.put("ProgressBar.foreground", new Color(0, 128, 0));
                UIManager.put("ProgressBar.selectionForeground", Color.WHITE);
                TTSApp window = new TTSApp();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public TTSApp() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame("文本朗读器");
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setLayout(new GridLayout(3, 1, 10, 10));

        // 顶部输入面板
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        inputPanel.setBackground(Color.WHITE);
        inputPanel.add(new JLabel("请输入文本："));
        textField = new JTextField(15);
        textField.setText("");
        inputPanel.add(textField);
        frame.add(inputPanel);

        // 进度条面板
        JPanel progressPanel = new JPanel(new BorderLayout());
        progressPanel.setBackground(Color.WHITE);
        progressBar = new JProgressBar();
        progressBar.setUI(new BasicProgressBarUI() {
            protected Color getSelectionBackground() {
                return Color.BLACK;
            }

            protected Color getSelectionForeground() {
                return Color.BLACK;
            }
        });
        progressBar.setForeground(new Color(0, 128, 0));
        progressBar.setPreferredSize(new Dimension(300, 20));
        progressBar.setStringPainted(true);
        progressBar.setVisible(false);
        progressPanel.add(progressBar, BorderLayout.CENTER);
        frame.add(progressPanel);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.setBackground(Color.WHITE);
        reverseButton = new JButton("倒序朗读");
        orderButton = new JButton("顺序朗读");
        buttonPanel.add(orderButton);
        buttonPanel.add(reverseButton);
        frame.add(buttonPanel);

        // 事件监听
        orderButton.addActionListener(e -> processText(false));
        reverseButton.addActionListener(e -> processText(true));
    }

    private void processText(boolean reverse) {
        String text = textField.getText();
        if (text.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "请输入文本！");
            return;
        }

        if (reverse) text = new StringBuilder(text).reverse().toString();

        String finalText = text;
        new SwingWorker<Void, Integer>() {
            @Override
            protected Void doInBackground() throws Exception {
                progressBar.setVisible(true);
                for (int i = 0; i <= 100; i++) {
                    Thread.sleep(15);
                    publish(i);
                }
                File audioFile = TtsHttpClient.generateSpeech(finalText);
                playAudio(audioFile.getAbsolutePath());
                return null;
            }

            @Override
            protected void process(java.util.List<Integer> chunks) {
                progressBar.setValue(chunks.get(chunks.size() - 1));
            }

            @Override
            protected void done() {
                try {
                    get();
                    progressBar.setValue(100);
                } catch (Exception ex) {
                    progressBar.setVisible(false);
                    JOptionPane.showMessageDialog(frame, "处理失败: " + ex.getMessage());
                }
            }
        }.execute();
    }

    private void playAudio(String filename) throws Exception {
        AudioInputStream audioIn = AudioSystem.getAudioInputStream(new File(filename));
        Clip clip = AudioSystem.getClip();
        clip.open(audioIn);
        clip.addLineListener(e -> {
            if (e.getType() == LineEvent.Type.STOP) {
                clip.close();
                new File(filename).delete();
            }
        });
        clip.start();
    }

    public static class TtsHttpClient {
        // ... 保持原有实现不变 ...
        public static final String HOST = "openspeech.bytedance.com";
        public static final String API_URL = "https://" + HOST + "/api/v1/tts";
        public static final String ACCESS_TOKEN = "mg69QYlBcQrmp-VNZ-fmXJFKVM8J58fI";

        public static File generateSpeech(String text) throws IOException {
            File tempFile = File.createTempFile("tts_", ".wav");
            String response = post(API_URL, JSON.toJSONString(new TtsRequest(text)));
            String data = response.split("\"data\":\"")[1].split("\"")[0];
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(Base64.getDecoder().decode(data));
            }
            return tempFile;
        }

        private static String post(String url, String json) throws IOException {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .header("Authorization", "Bearer; " + ACCESS_TOKEN)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                return response.body().string();
            }
        }
    }
}